/*
 * wind.c
 *
 *  Created on: Sep 5, 2020
 *      Author: daniel
 */

#include "wind.h"
#include "crc.h"
#include "ws_data.h"

extern UART_HandleTypeDef hlpuart1;

static uint8_t		Wind_RequestData[] = {0x01, 0x03, 0x00, 0x0A, 0x00, 0x02, 0xE4, 0x09};

static uint16_t		Wind_dir = 0;
static uint16_t		Wind_speed = 0;
static bool			Wind_Data_OK = false;

#define RXBUFFERSIZE		9
uint8_t	aRxBuffer[RXBUFFERSIZE];

extern uint8_t	full_flag;

void Wind_Read()
{
	// 使用DMA发送Modbus的请求数据
	HAL_UART_Transmit_DMA(&hlpuart1, Wind_RequestData, sizeof(Wind_RequestData));
	Wind_dir = 0;
	Wind_speed = 0;
	Wind_Data_OK = 0;

	full_flag |= FULL_LPUART_DMA;
}

void Wind_Recv()
{
	// DMA发送完成，然后启动接收。因为LPUART不能在STOP模式使用DMA接收，只能使用中断方式接收
	// 用中断方式接收指定长度数据，因为modbus反馈回来的风速和风向数据恒定长度
	HAL_UART_Receive_IT(&hlpuart1, aRxBuffer, RXBUFFERSIZE);

	full_flag &= ~(FULL_LPUART_DMA);

}

void Wind_RecvOK()
{
	Wind_Data_OK = true;
}

void Wind_GetData(uint16_t* dir, uint16_t* speed)
{
	uint16_t		crc_result;

	if (Wind_Data_OK)
	{
		// CRC校验
		crc_result = MODBUS_CRC16_v2(aRxBuffer, RXBUFFERSIZE - 2);
		if (crc_result == (aRxBuffer[7] + (aRxBuffer[8] << 8)))
		{

			// 风向
			Wind_dir = (aRxBuffer[5] << 8) + aRxBuffer[6];

			// 风速
			Wind_speed = (aRxBuffer[3] << 8) + aRxBuffer[4];
		}
	}
	else
	{
		// time out, 得停止中断接收
		HAL_UART_AbortReceive(&hlpuart1);
	}

	*dir = Wind_dir;
	*speed = Wind_speed;
}
